<?php
/*
 * @Descripttion: 
 * @Author: dedeye
 * @Date: 2020-02-25 17:45:52
 * @LastEditors: dedeye
 * @LastEditTime: 2020-03-01 11:58:19
 */

namespace app\admin\controller;

use think\Controller;
use think\facade\Session;
use app\admin\model\Admin as AdminModel;
use app\common\util\ReturnCode;
use app\common\util\Tool;

class Login extends Controller
{
    public function index()
    {
        if(Session::has('admin_id') && Session::has('admin_code')) {
            $code = Tool::opensslEncode(Session::get('admin_id'));
            if($code !== false) {
                if($code == Session::get('admin_code')) {
                    return redirect('admin/index/index');
                }
            }
        }
        if(!request()->isPost() || !request()->isAjax()) {
            return $this->fetch();
        }
        $data = input('post.');
        $validate = new \app\admin\validate\AdminValidate;
        if (!$validate->scene('login')->check($data)) {
            return resultJson(ReturnCode::PARAM_ERROR, $validate->getError());
        }
        $admin = AdminModel::where('username', $data['username'])->find();
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '用户不存在');
        }
        if(md5($data['password'].$admin->salt) !== $admin->password) {
            return resultJson(ReturnCode::PARAM_INVALID, '用户名或密码错误');
        }
        Session::set('admin_id', $admin->id);
        Session::set('admin_name', $admin->nickname);
        Session::set('admin_code', Tool::opensslEncode($admin->id));
        return resultJson(ReturnCode::SUCCESS, '登录成功', url('admin/index/index'));
    }

    public function verify()
    {
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    36,    
            // 验证码位数
            'length'      =>    4,   
            // 关闭验证码杂点
            'useNoise'    =>    true, 
        ];
        $captcha = new \think\captcha\Captcha($config);
        return $captcha->entry();
    }
}
